import gcoord from "../../miniprogram_npm/gcoord/dist/gcoord";
Page({
  data: {
    // 当前的位置
    latitude: "",
    longitude: "",
    latitude1: "",
    longitude1: "",
    // 画圆
    circles: [],
    nearByList: [], // 企业后台接口信息集合
    originList: [], // 原始列表数据
    // markers: [], // 企业标记点集合
    markers: [],
    placeData: {},
    token: "",
    height: "600rpx",
    data: [],
    data1: [],
    positi: [],
    wxMarkerData: [],
    originalData: [],
    thsisab: "1",
    markerId: "",
    zb: "",
    qiyeTypeList1: [{
        name: "大型企业",
        url1: "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/map/1.png",
      },
      {
        name: "小微企业",
        url1: "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/map/7.png",
      },
      {
        name: "无贷企业",
        url1: "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/map/6.png",
      },
      {
        name: "外贸企业",
        url1: "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/map/5.png",
      },
      {
        name: "瞪羚企业",
        url1: "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/map/2.png",
      },
      {
        name: "政府采购",
        url1: "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/map/8.png",
      },
      {
        name: "高新技术",
        url1: "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/map/3.png",
      },
      {
        name: "更多",
        url1: "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/map/4.png",
      },
    ],
    qiyeAllList1: [
      "大型企业",
      "小微企业",
      "无贷企业",
      "外贸企业",
      "瞪羚企业",
      "政府采购",
      "高新技术",
      "更多",
    ],
    actionType: 1, // 默认展开
    pageNum: 1,
    total: "", // 附近企业总数
    activeTabIndex: 0, // 默认附近企业
    tabLists: [{
        name: "附近500m企业",
      },
      {
        name: "附近1km企业",
      },
      {
        name: "营收500万-1000万",
      },
      {
        name: "营收1000万以上",
      },
      {
        name: "外贸进口增长",
      },
      {
        name: "外贸出口增长",
      },
      {
        name: "资产负债率50%-100%",
      },
      {
        name: "专利发明增加",
      },
      // {
      //   name: "国有银行有贷",
      // },
      // {
      //   name: "有小额贷款",
      // },
      // {
      //   name: "有融资需求企业",
      // },
      // {
      //   name: "未结清信贷企业",
      // },
      // {
      //   name: "未结清小额贷款企业",
      // },
      // {
      //   name: "纳税A级企业",
      // },
      // {
      //   name: "用水企业",
      // },
      // {
      //   name: "用电企业",
      // },
      // {
      //   name: "缴纳社保企业",
      // },
      // {
      //   name: "缴纳公积金企业",
      // },
    ],
    zdcyList: [{
        name: "重点产业",
      },
      {
        name: "电子信息",
      },
      {
        name: "数字经济",
      },
      {
        name: "高端装备制造",
      },
      {
        name: "生物医药",
      },
      {
        name: "集成电路",
      },
      {
        name: "汽车零部件",
      },
      {
        name: "先进材料",
      },
      {
        name: "软件服务",
      },
      {
        name: "航空航天",
      },
    ],
    cyTabIndex: "",
    extraObj: {}, // 额外的查询条件
    distance: "0.5", // 距离
    actionTypeTest: 1,
    isVip: '',
    loading: true
  },

  async initVip() {
    // let data={needCount :'N'}
    const vipCode = await getApp().globalData.checkVipStatus('N')
    this.setData({
      isVip: vipCode !== 'ordinary' && vipCode !== 'notVipBindFI' && vipCode !== 'visitor'
    })
  },

  // 页面解析完成后执行
  onReady: function () {
    // 步骤一、常见地图实例对象
    this.mapCtx = wx.createMapContext("myMap");
    this.locationBack();
  },
  onLoad: function (e) {
    this.setData({
      loading: true
    })
    this.initVip()
    const that = this;
    // 获取当前的位置信息
    getApp().globalData.getLocation({
      type: "gcj02",
      success(res) {
        // 获取当前的定位
        console.log(res, '获取当前的定位')
        that.getLocationNow(res);
        that.initInfoByCenter(res);
      },
    });
    // this.initInfos();
  },

  /**
   * methods
   */
  getLocationNow(info) {
    console.log(this.transMarker([info.longitude, info.latitude])[1],this.transMarker([info.longitude, info.latitude])[0],'搜索的传输')
    getApp()
      .globalData.request(
        "/map/inverseGeocode", {
          lat: this.transMarker([info.longitude, info.latitude])[1],
          lng: this.transMarker([info.longitude, info.latitude])[0],
          needToken: true
        },
        "POST"
      )
      .then((res) => {
        const rstObj = res;
        this.setData({
          zb: rstObj.data.replace("苏州市苏州", "苏州市"),
        });
      });
  },
  // 获取页面节点信息的方法(nodeName 节点id名称)
  getNodeInfo(nodeName) {
    const query = this.createSelectorQuery();
    query.select(`#${nodeName}`).boundingClientRect();
    query.selectViewport().scrollOffset();
    query.exec((res) => {
      this.setData({
        scrollTop: res[0].height
      });
    });
  },
  initInfoByCenter(res) {
    console.log(res, '3333')
    this.setData({
      longitude: this.transMarker([res.longitude, res.latitude])[0],
      latitude: this.transMarker([res.latitude, res.latitude])[1],
      longitude1: res.longitude,
      latitude1: res.latitude,
    });
    console.log(this.data.longitude, '444')
    // center info
    this.setData({
      circles: [{
        latitude: res.latitude,
        longitude: res.longitude,
        color: "#7cb5ec88",
        opacity: 0.2,
        fillColor: "#7cb5ec88",
        radius: 600,
        strokeWidth: 2,
      }, ],
    });

    // 数据初始化
    this.initInfos();
  },
  // 初始化数据
  async initInfos() {
    // 获取周边企业的坐标
    await this.getNearByInfos();
    // 初始化markers
    this.initMarkers();
  },

  // 获取附近企业的坐标
  async getNearByInfos() {
   if(!this.data.loading) {
     wx.showLoading()
   }
  //   let userId=''
  //  if(wx.getStorageSync('userInfo').userId){
  //   userId=wx.getStorageSync('userInfo').userId
  //  }
    const params = {
      // userId:userId,
      distance: this.data.distance,
      userLng: this.data.longitude,
      userLat: this.data.latitude,
      // userLng: 120.68151,
      // userLat: 31.322478,
      sortColumn: "creditScore",
      sortRule: "desc",
      pageBO: {
        pageSize: 50,
        pageNum: this.data.pageNum,
      },
      needToken: true
    };
    console.log({
      ...params,
      ...this.data.extraObj
    }, "附近企业查询条件");
    // /map/lookAround
    const {
      list,
      total
    } = await getApp().globalData.request(
      "/map/lookAroundV2", {
        ...params,
        ...this.data.extraObj
      },
      "POST"
    );
    setTimeout(() => {
      this.setData({
        loading: false
      })
      wx.hideLoading()
    }, 500);
    console.log(list, 'list');
    // 原始列表数据
    this.setData({
      originList: this.data.originList.concat(list),
      total: total,
    });
    // 处理数据
    const resInfos = this.findSameList(this.data.originList);
    this.setData({
      nearByList: resInfos,
    });
  },

  // 初始化点标记
  initMarkers() {
    const markers = [];
    this.data.nearByList.forEach((val, index) => {
  

      const zuobiao = this.transMarker1([val[0].longitude, val[0].latitude]);
      const longitude = zuobiao[0];
      const latitude = zuobiao[1];
      markers.push({
        id: index,
        latitude: latitude,
        longitude: longitude,
        name: val[0].d2CorpName,
        corpKey: val[0].corpKey,
        iconPath: "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/zhoubian1.png",
        desc: "我现在的位置",
        title: val[0].d2CorpName,
        width: 14,
        height: 21,
        callout: {
          content: `${val[0].d2CorpName}${val.length > 0 ? "等" + val.length + "家企业" : ""
            },点击查看`,
          color: "#ffffff",
          bgColor: "#505d58", //需要6位的色值有效
          fontSize: 14,
          borderRadius: 2,
          padding: 5,
          display: "BYCLICK", //'BYCLICK':点击显示; 'ALWAYS':常显
        },
      });
    });
    // 中心点自定义样式
    // markers.push({
    //   id: 9999,
    //   latitude: this.data.circles[0].latitude,
    //   longitude: this.data.circles[0].longitude,
    //   name: "",
    //   iconPath:
    //     " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/center-location2.png",
    //   desc: "我现在的位置",
    //   title: "",
    //   width: 23,
    //   height: 31,
    // });
    console.log(markers,'markersmarkers')
    this.setData({
      markers: markers,
    });
  },

  // 打开模糊地址搜索
  openSearch() {
    const that = this;
    wx.chooseLocation({
      success(res) {
        that.setData({
          // zb: JSON.stringify({
          //   longitude: res.longitude,
          //   latitude: res.latitude,
          // }),
        });
        // 重新定位中心点，分页参数重置，原markers清除
        that.setData({
          pageNum: 1,
        });
        that.setData({
          originList: [],
        });
        that.initInfoByCenter(res);
        // that.initInfoByCenter({ longitude: 120.642391, latitude: 31.369189 });
        console.log(res, "成功回调");
      },
      fail(res) {
        console.log(res, "失败回调");
      },
      complete(res) {
        console.log(res, "结束回调");
      },
    });
  },

  // 坐标系转化
  transMarker(item) {
    const resae = gcoord.transform(
      [item[0], item[1]],
      gcoord.GCJ02, // 当前坐标系
      gcoord.BD09 // 目标坐标系
    );
    console.log(resae, 'resaeresae')
    return resae;
  },

  // 中心点坐标转化
  transMarker1(item) {
    const resae = gcoord.transform(
      [item[0], item[1]],
      gcoord.BD09, // 当前坐标系
      gcoord.GCJ02 // 目标坐标系
    );
 
    return resae;
  },

  // 查找重复的数据,并且重新排列
  findSameList(item) {
    console.log(item,'item')
    const needList = JSON.parse(JSON.stringify(item));
    // 先去重复
    const singleList = this.removeDuplicateObj(needList);
    const showList = [];
    singleList.forEach((val, index) => {
      const itemList = [];
      needList.forEach((pre) => {
        if (val.latitude === pre.latitude) {
          itemList.push(pre);
        }
      });
      showList.push(itemList);
    });
    return showList;
  },

  removeDuplicateObj(arr) {
    let obj1 = {};
    let obj2 = {};
    let arr1 = [];
    let arr2 = [];
    arr1 = arr.reduce((newArr, next) => {
      obj1[next.latitude] ? "" : (obj1[next.latitude] = 1 && newArr.push(next));
      return newArr;
    }, []);
    arr2 = arr1.reduce((newArr, next) => {
      obj2[next.longitude] ?
        "" :
        (obj2[next.longitude] = 1 && newArr.push(next));
      return newArr;
    }, []);
    return arr2;
  },

  // 跳转企业详情或者企业列表
  async markerCalloutTap(e) {
    const vipCode = await getApp().globalData.checkVipStatus()
    if (vipCode === 'ordinary' || vipCode === 'notVipBindFI' || vipCode === 'visitor') {
      wx.showModal({
        title: '提示',
        content: '该功能为VIP会员功能，请联系客服了解详情。',
        showCancel: false,
        confirmText: '确定',
        success: function () {}
      })
      return
    }
    if (this.data.nearByList[e.markerId].length > 1) {
      // 跳转到列表页面
      wx.navigateTo({
        url: `../../packageB/pages/businesses/businesses?businesses=${JSON.stringify(
          this.data.nearByList[e.markerId]
        )}`,
      });
    } else {
      // 跳转到详情页面
      wx.navigateTo({
        url: `/pages/mapDetail/mapDetail?corpKey=${this.data.nearByList[e.markerId][0].corpKey
          }&latitude=${this.data.nearByList[e.markerId][0].latitude}&longitude=${this.data.nearByList[e.markerId][0].longitude
          }&distance=${this.data.nearByList[e.markerId][0].distance}`,
      });
    }
  },

  // 扩展
  open() {
    this.setData({
      actionType: 1,
    });
    this.getNodeInfo("sticky1");
    setTimeout(() => {
      this.setData({
        actionTypeTest: 1,
      });
    }, 500);
  },

  // 收缩
  close() {
    this.setData({
      actionType: 0,
      actionTypeTest: 0,
    });
  },

  toprodetail(e) {
    wx.navigateTo({
      url: `/pages/mapDetail/mapDetail?corpKey=${e.detail.corpKey}&latitude=${e.detail.latitude}&longitude=${e.detail.longitude}&distance=${e.detail.distance}`,
    });
  },
  // 滑动底部加载更多
  async scrollBottom() {
    if (this.data.isVip) {
      this.setData({
        pageNum: ++this.data.pageNum,
      });
      this.initInfos();
    } else {
      const vipCode = await getApp().globalData.checkVipStatus()
      if (vipCode === 'ordinary' || vipCode === 'notVipBindFI' || vipCode === 'visitor') {
        wx.showModal({
          title: '提示',
          content: '该功能为VIP会员功能，请联系客服了解详情。',
          showCancel: false,
          confirmText: '确定',
          success: function () {}
        })
        return
      }
    }
  },

  location(e) {
    const longitude = this.transMarker1([
      e.currentTarget.dataset.one.longitude,
      e.currentTarget.dataset.one.latitude,
    ])[0];
    const latitude = this.transMarker1([
      e.currentTarget.dataset.one.longitude,
      e.currentTarget.dataset.one.latitude,
    ])[1];
    wx.openLocation({
      latitude: latitude,
      longitude: longitude,
      name: e.currentTarget.dataset.one.d2CorpName,
      address: e.currentTarget.dataset.one.d2Dom,
      scale: 18,
    });
  },
  // 切换分类
  async clickCy1(e) {
    const vipCode = await getApp().globalData.checkVipStatus()
    if (vipCode === 'ordinary' || vipCode === 'notVipBindFI' || vipCode === 'visitor') {
      wx.showModal({
        title: '提示',
        content: '该功能为VIP会员功能，请联系客服了解详情。',
        showCancel: false,
        confirmText: '确定',
        success: function () {}
      })
      return
    }
    // if (e.currentTarget.dataset.index === 0) {
    //   wx.navigateTo({
    //     url: `../zdcy/zdcy?latitude=${this.data.latitude1}&longitude=${this.data.longitude1}`,
    //   });
    // } else 
    if (e.currentTarget.dataset.index === 7) {
      wx.navigateTo({
        url: `../mapMore/mapMore?latitude=${this.data.latitude1}&longitude=${this.data.longitude1}`,
      });
    } else {
      wx.navigateTo({
        url: `../qiye/qiye?titleName=${this.data.qiyeAllList1[e.currentTarget.dataset.index]
          }&latitude=${this.data.latitude1}&longitude=${this.data.longitude1}`,
      });
    }
  },
  clickCy2(e) {
    wx.navigateTo({
      url: `../qiye/qiye?titleName=${this.data.qiyeAllList2[e.currentTarget.dataset.index]
        }`,
    });
  },

  // 返回到当前定位视窗
  locationBack() {
    this.mapCtx.moveToLocation();
  },


  async isCanClick() {
    const vipCode = await getApp().globalData.checkVipStatus()
    if (vipCode === 'ordinary' || vipCode === 'notVipBindFI' || vipCode === 'visitor') {
      wx.showModal({
        title: '提示',
        content: '该功能为VIP会员功能，请联系客服了解详情。',
        showCancel: false,
        confirmText: '确定',
        success: function () {}
      })
      return
    }
  },

  async tabTuijian(e) {
    this.setData({
      extraObj: {},
    });
    switch (e.detail.title) {
      case "附近500m企业":
        const params0 = {
          distance: 0.5,
        };
        this.setData({
          extraObj: params0,
        });
        this.originInfo();
        break;
      case "营收500万-1000万":
        const params1 = {
          businessIncomeLowerLimit: "500",
          businessIncomeUpperLimit: "1000",
        };
        this.setData({
          extraObj: params1,
        });
        this.originInfo();
        break;
      case "营收1000万以上":
        const params2 = {
          businessIncomeLowerLimit: "1000",
          businessIncomeUpperLimit: "50000",
        };
        this.setData({
          extraObj: params2,
        });
        this.originInfo();
        break;
      case "有融资需求企业":
        const params3 = {
          isLoan: "1",
        };
        this.setData({
          extraObj: params3,
        });
        this.originInfo();
        break;
      case "未结清信贷企业":
        const params4 = {
          qutstandingLoans: "1",
        };
        this.setData({
          extraObj: params4,
        });
        this.originInfo();
        break;
      case "未结清小额贷款企业":
        const params5 = {
          qutstandingSmallLoans: "1",
        };
        this.setData({
          extraObj: params5,
        });
        this.originInfo();
        break;
      case "纳税A级企业":
        const params6 = {
          taxALeavel: "1",
        };
        this.setData({
          extraObj: params6,
        });
        this.originInfo();
        break;
      case "用水企业":
        const params7 = {
          isWater: "1",
        };
        this.setData({
          extraObj: params7,
        });
        this.originInfo();
        break;
      case "用电企业":
        const params8 = {
          isElec: "1",
        };
        this.setData({
          extraObj: params8,
        });
        this.originInfo();
        break;
      case "缴纳社保企业":
        const params9 = {
          isSecurity: "1",
        };
        this.setData({
          extraObj: params9,
        });
        this.originInfo();
        break;
      case "缴纳公积金企业":
        const params10 = {
          isFund: "1",
        };
        this.setData({
          extraObj: params10,
        });
        this.originInfo();
        break;
      case "附近1km企业":
        const params11 = {
          distance: 1.0,
        };
        this.setData({
          extraObj: params11,
        });
        this.originInfo();
        break;
      case "外贸进口增长":
        const params12 = {
          importTrend: '1',
        };
        this.setData({
          extraObj: params12,
        });
        this.originInfo();
        break;
      case "外贸出口增长":
        const params13 = {
          exportTrend: '1',
        };
        this.setData({
          extraObj: params13,
        });
        this.originInfo();
        break;
      case "资产负债率50%-100%":
        const params14 = {
          debtLowerLimit: '50',
          debtUpperLimit: '100',
        };
        this.setData({
          extraObj: params14,
        });
        this.originInfo();
        break;
      case "专利发明增加":
        const params15 = {
          patentTrend: '1',
        };
        this.setData({
          extraObj: params15,
        });
        this.originInfo();
        break;
      case "国有银行有贷":
        const params16 = {
          loanStateBank: '1',
        };
        this.setData({
          extraObj: params16,
        });
        this.originInfo();
        break;
      case "有小额贷款":
        const params17 = {
          smallLoan: '1',
        };
        this.setData({
          extraObj: params17,
        });
        this.originInfo();
        break;
      default:
        break;
    }
  },

  async tabTuijianCy(e) {
    const params = {
      keyIndustries: e.detail.title === "重点产业" ? "" : e.detail.title + "产业",
    };
    this.setData({
      extraObj: params,
    });
    this.originInfo();
  },

  // 初始化
  originInfo() {
    this.setData({
      pageNum: 1,
      originList: [],
    });
    this.initInfos();
  },
});